<?php
	$start_process = (float) array_sum(explode(' ',microtime()));
	ini_set('display_errors', 1);
	error_reporting(E_ALL);
	
	require 'src/facebook.php';
	
	$facebook = new Facebook(array(
	  'appId'  => "422052821143625",
	  'secret' => "e57e73495992f3ef2ec8581e9e9d2a7f",
	));
	
	$user_id = $facebook->getUser();
	
	if($user_id == 0 || $user_id == "")
	{
		$login_url = $facebook->getLoginUrl(array(
		//'redirect_uri'         => "http://apps.facebook.com/rapid-apps/",
		'scope'      => "email,publish_stream,user_hometown,user_location,user_photos,friends_photos,
					user_photo_video_tags,friends_photo_video_tags,user_videos,video_upload,friends_videos"));
		
		echo "<script type='text/javascript'>top.location.href = '$login_url';</script>";
		exit();
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<div id="fb-root">
<p><a target="_top" href="http://apps.facebook.com/rapid-apps/">Back</a></p>
<?php
	$db_host = "localhost";
    $db_name = "facebook";
    $db_username = "root";
    $db_password = "";
 
    $dbh = mysql_connect($db_host, $db_username, $db_password) or die("Unable to connect to MySQL");
    mysql_query('SET NAMES "utf8"');
    mysql_select_db($db_name, $dbh) or die("Could not select $db_name");
	
	echo "<p>Your Facebook Id: " . $user_id . "</p>";
	
	$total_friend = 0;
	$sql = "select * from fb_users where uid='{$user_id}'";
	$q = mysql_query($sql);
	if(!$r = mysql_fetch_array($q)){
		$friends = $facebook->api("/me/friends");
	
		$total_friend = count($friends["data"]);
		
		mysql_query("insert into fb_users(uid, total_friend) values (" . $user_id . ", " . $total_friend . ")");
		
		$count = 0;
		
		$friend_ids = "";
		$query = "insert into fb_friends(uid, friend_id, friend_name)values";
		$values = "";
		
		foreach($friends["data"] as $item){


			$friend_ids .= $item["id"] . ",";
			$values .= "('{$user_id}', '{$item["id"]}', '" . mysql_escape_string($item["name"]) . "')," ;
		}
		
		if($values != ""){
			$values = substr($values, 0, strlen($values) -1);
			$values .= ";";
		}
		
		$query .= $values;
		
		mysql_query($query);
	}
	else
	{
		$total_friend = $r["total_friend"];
	}
	
	$page = 0;
	
	if(isset($_REQUEST["page"]) && $_REQUEST["page"] != "")
		$page = (int)$_REQUEST["page"];
	if($page == 0)$page = 1;
	
	$page_size = 10;
	
	$total_pages = ceil($total_friend/$page_size);
				
	if($page > $total_pages)
		$page = $total_pages;
	
	$start = $total_pages > 0 ? (( $page * $page_size ) - $page_size) : 0;
	$end = $start + $page_size;
	$start = $start <= 1 ? 0 : $start;
	$sql .=" LIMIT $start, $page_size";
	
	$sql = "select * from fb_friends where uid='{$user_id}' LIMIT $start, $page_size";
	
	$q = mysql_query($sql);
	$friend_table = "";
	$friend_table .= "<table border='1'>";
	$friend_table .= "<tr><th>Friend Name</th><th>Friend Facebook Id</th><th>Friend Picture</th></tr>";
	while($r = mysql_fetch_assoc($q))
	{
		$friend_table .= "<tr><td>" . $r["friend_id"] . "</td><td>" . $r["friend_name"] . "</td><td align='center'><img src='http://graph.facebook.com/" . $r["friend_id"] . "/picture'></td></tr>";
	}
	$friend_table .= "</table>";
	
	echo "<h3>Your Facebook Friend List ({$total_friend} friends)</h3>";
	echo $friend_table;
	
	echo create_page_navigation($total_friend, $page, $page_size, "http://apps.facebook.com/rapid-apps/load-friends.php", "");
	
	function create_page_navigation($total_record, $current_page_, $item_per_page, $url, $query_string)
    {
        $current_page = $current_page_ + 1;
        $pagerange = 10;
        $num_pages = ($total_record % $item_per_page == 0) ? ceil($total_record / $item_per_page) : ceil($total_record / $item_per_page);

        $rangecount = 0;
        $table = "<table>";
		$table .= "<tr>";
        $table .= "<td>{$current_page_ } / {$num_pages} </td>";
        if ($current_page_ > 1)
        {
            $tmp = $current_page_ - 1;
            $table .= "<td><a target='_top' href='" . $url . "?page=" . $tmp . "&&" . $query_string . "'><</a></td>";
        }

        if ($num_pages > 1)
        {
            $rangecount = ceil($num_pages / $pagerange);

            $startpage = 0;
            $count = 0;
            for ($i = 1; $i < $rangecount + 1; $i++)
            {
                $startpage = (($i - 1) * $pagerange) + 1;
                $count = min($i * $pagerange, $num_pages);
                if ((($current_page >= $startpage) && ($current_page <= ($i * $pagerange))))
                {
                    for ($j = $startpage; $j < $count + 1; $j++)
                    {
                        if ($j == $current_page_)
                        {
                            $table .= "<td><b>" . $j . "<b></td>";
                        }
                        else
                        {
                            $table .= "<td><a target='_top' href='" . $url . "?page=" . $j . "&&" . $query_string . "'>" . $j . "</a></td>";
                        }
                    }
                }
            }
        }
        if ($current_page_ < $num_pages)
        {
            $tmp2 = $current_page_ + 1;
            $table .= "<td><a target='_top' href='" . $url . "?page=" . $tmp2 . "&&" . $query_string . "'>></a></td>";
        }
        $table .= "</tr></table>";
        return $table;
    }
?>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
	FB.Canvas.setSize({ width: 520, height: 1500 });
</script>
</body>
</html>
<?php
	$end_process = (float) array_sum(explode(' ',microtime()));
	echo "<p>Execution time: ". sprintf("%.4f", ($end_process-$start_process))." seconds</p>";
?>